package controllers;

import java.awt.event.ActionEvent;
import java.util.Vector;

import dialogs.DeleteTupleDialog;
import dialogs.InsertTupleDialog;

import models.ReturnItemModel;

import system.View;

public class ReturnItemController extends AbstractMenuItemController {
	private ReturnItemModel return_item = new ReturnItemModel();

	public ReturnItemController(View v) {
		super(v);
		abstractModel = return_item;
		return_item.addExceptionListener(this);
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		String actionCommand = e.getActionCommand();

		if (actionCommand.equals("Remove Item from Returns"))
			showDialogWindow(new DeleteTupleDialog(view, actionCommand, "Key",
					new String[] { "Return Transaction ID: ", "Item UPC: " },
					this));

		else if (actionCommand.equals("Add Item to Returns"))
			showDialogWindow(new InsertTupleDialog(view, actionCommand,
					"Returned Item", new String[] { "Return Transaction ID: ",
							"Item UPC: ", "Purchase Quantity: ", }, this));
	}

	@Override
	public int validateInsert(Vector<String> s) {
		if (s.size() != 3)
			return VALIDATIONERROR;

		try {
			int upc;
			int retid;
			int quantity;

			if (s.get(0).trim().length() != 0)
				retid = Integer.valueOf(s.get(0).trim());
			else return VALIDATIONERROR;
			if (s.get(1).length() != 0)
				upc = Integer.valueOf(s.get(1).trim());
			else return VALIDATIONERROR;
			if (s.get(2).length() != 0)
				quantity = Integer.valueOf(s.get(2).trim());
			else return VALIDATIONERROR;

			view.updateStatusBar("Inserting item to be returned...");

			if (return_item.insert(retid, upc, quantity)) return operationSuccess();
			else
				return operationFailure();
		} catch (NumberFormatException ex) {
			return VALIDATIONERROR;
		}
	}

	@Override
	public int validateDelete(Vector<String> s) {
		if (s.size() != 2)
			return VALIDATIONERROR;

		try {
			int retid;
			int upc;

			if (s.get(0).trim().length() != 0)
				retid = Integer.valueOf(s.get(0).trim());
			else return VALIDATIONERROR;
			if (s.get(1).trim().length() != 0)
				upc = Integer.valueOf(s.get(0).trim());
			else return VALIDATIONERROR;
			view.updateStatusBar("Deleting item returned...");

			if (return_item.delete(retid, upc)) return operationSuccess();
			else return operationFailure();
		} catch (NumberFormatException ex) {
			return VALIDATIONERROR;
		}
	}
}